//
//  AppDelegate.m
//  WKWebVIewDemo
//
//  Created by Yonger on 2018/7/19.
//  Copyright © 2018年 WKWebView. All rights reserved.
//
#import "ZQQrResultPage.h"
#import "ErWeiMaPage.h"
#import "AppDelegate.h"
#import "KUtilsNavigationViewController.h"
#import "UtilsContentMaskController.h"
#import "CYLTabBarController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "ZQNavViewController.h"
#import "ZQLoginPage.h"
#import "ZQMainPage.h"
@interface AppDelegate ()<CYLTabBarControllerDelegate,UITabBarControllerDelegate>
/** nac */
@property (nonatomic, weak) ZQNavViewController *nav;
@end

@implementation AppDelegate
- (ZQNavViewController *)nav
{
    if (!_nav) {
        ZQNavViewController *nav = [[ZQNavViewController alloc] init];
        _nav = nav;
    }
    return _nav;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    [self creamrelamtable];
    [self setKeyboard];
    self.isFirstLoad = YES;
    [self startNetworkMonitoring];
//    [self customizeTabBarForController:self.tabBarController];
//    [self setupViewControllers];
    ZQLoginPage *rootViewController = [ZQLoginPage new];
//    ZQQrResultPage *rootViewController = [ZQQrResultPage new];

    rootViewController.title = @"管理员登陆";
    ZQNavViewController *nav = [[ZQNavViewController alloc] initWithRootViewController:rootViewController];
    self.nav = nav;
    RegisterNotify(kTokenFailedNotification, @selector(tokenPopVc));

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UIColor whiteColor]];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)tokenPopVc
{
    ZQLoginPage *controller = self.nav.viewControllers[0];
    
    [self.nav popToViewController:controller animated:YES];
}

- (void)dealloc
{
    RemoveNofify;
}

- (void)creamrelamtable{
    
    RLMRealmConfiguration *config =[RLMRealmConfiguration defaultConfiguration];
    // 数据库本地路径
    config.schemaVersion=2;
    // 设置闭包，这个闭包将会在打开低于上面所设置版本号的 Realm 数据库的时候被自动调用
    config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
        NSLog(@"%llu",oldSchemaVersion);
        
        // 目前我们还未进行数据迁移，因此 oldSchemaVersion == 0
        if (oldSchemaVersion < 1) {
            // 什么都不要做！Realm 会自行检测新增和需要移除的属性，然后自动更新硬盘上的数据库架构
        }
    };
    
    [RLMRealmConfiguration setDefaultConfiguration:config];
    
    // 现在我们已经告诉了 Realm 如何处理架构的变化，打开文件之后将会自动执行迁移
    [RLMRealm defaultRealm];
    NSLog(@"%@",  config.fileURL);
    
    
}


- (void)setKeyboard
{
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    
    keyboardManager.enable = YES; // 控制整个功能是否启用
    
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    
    keyboardManager.shouldShowTextFieldPlaceholder = YES; // 是否显示占位文字
    
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
    
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离

}

- (void)customizeInterfaceWithTabBarController:(CYLTabBarController *)tabBarController {
    //设置导航栏
    [self setUpNavigationBarAppearance];
    
    [tabBarController hideTabBadgeBackgroundSeparator];
    //添加小红点
    UIViewController *viewController = tabBarController.viewControllers[0];
    UIView *tabBadgePointView0 = [UIView cyl_tabBadgePointViewWithClolor:RANDOM_COLOR radius:4.5];
    [viewController.tabBarItem.cyl_tabButton cyl_setTabBadgePointView:tabBadgePointView0];
   // 显示右上角区域
    [viewController cyl_showTabBadgePoint];
    
//    UIViewController *viewController2 = tabBarController.viewControllers[1];
    UIView *tabBadgePointView1 = [UIView cyl_tabBadgePointViewWithClolor:RANDOM_COLOR radius:4.5];
    @try {
//        [viewController2.tabBarItem.cyl_tabButton cyl_setTabBadgePointView:tabBadgePointView1];
        // 显示右上角区域
//        [viewController2 cyl_showTabBadgePoint];
        [tabBarController.viewControllers[1] cyl_setTabBadgePointView:tabBadgePointView1];
        
        [tabBarController.viewControllers[1] cyl_showTabBadgePoint];


        UIView *tabBadgePointView2 = [UIView cyl_tabBadgePointViewWithClolor:RANDOM_COLOR radius:4.5];
        [tabBarController.viewControllers[2] cyl_setTabBadgePointView:tabBadgePointView2];
        [tabBarController.viewControllers[2] cyl_showTabBadgePoint];

//        [tabBarController.viewControllers[3] cyl_showTabBadgePoint];

        //添加提示动画，引导用户点击
        [self addScaleAnimationOnView:tabBarController.viewControllers[1].cyl_tabButton.cyl_tabImageView repeatCount:20];
    } @catch (NSException *exception) {}
}


/**
 *  设置navigationBar样式
 */
- (void)setUpNavigationBarAppearance {
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    
    UIImage *backgroundImage = nil;
    NSDictionary *textAttributes = nil;
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        backgroundImage = [UIImage imageNamed:@"navigationbar_background_tall"];
        
        textAttributes = @{
                           NSFontAttributeName : [UIFont boldSystemFontOfSize:18],
                           NSForegroundColorAttributeName : [UIColor blackColor],
                           };
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        backgroundImage = [UIImage imageNamed:@"navigationbar_background"];
        textAttributes = @{
                           UITextAttributeFont : [UIFont boldSystemFontOfSize:18],
                           UITextAttributeTextColor : [UIColor blackColor],
                           UITextAttributeTextShadowColor : [UIColor clearColor],
                           UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetZero],
                           };
#endif
    }
    
    [navigationBarAppearance setBackgroundImage:backgroundImage
                                  forBarMetrics:UIBarMetricsDefault];
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}


//缩放动画
- (void)addScaleAnimationOnView:(UIView *)animationView repeatCount:(float)repeatCount {
    //需要实现的帧动画，这里根据需求自定义
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.scale";
    animation.values = @[@1.0,@1.3,@0.9,@1.15,@0.95,@1.02,@1.0];
    animation.duration = 1;
    animation.repeatCount = repeatCount;
    animation.calculationMode = kCAAnimationCubic;
    [animationView.layer addAnimation:animation forKey:nil];
}

//旋转动画
- (void)addRotateAnimationOnView:(UIView *)animationView {
    // 针对旋转动画，需要将旋转轴向屏幕外侧平移，最大图片宽度的一半
    // 否则背景与按钮图片处于同一层次，当按钮图片旋转时，转轴就在背景图上，动画时会有一部分在背景图之下。
    // 动画结束后复位
    animationView.layer.zPosition = 65.f / 2;
    [UIView animateWithDuration:0.32 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        animationView.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
    } completion:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.70 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
            animationView.layer.transform = CATransform3DMakeRotation(2 * M_PI, 0, 1, 0);
        } completion:nil];
    });
}


- (void)startNetworkMonitoring{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    self.networkStatus = manager.networkReachabilityStatus;
    [manager startMonitoring];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingStatusDidChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

- (void)networkingStatusDidChanged:(NSNotification*)info{
    NSDictionary *inforDict = [info userInfo];
    NSString *statusStr = [UtilsConfigModel getString:inforDict key:AFNetworkingReachabilityNotificationStatusItem];
    if (statusStr == nil || [statusStr isBlankString]) {
        statusStr = [UtilsConfigModel getString:inforDict key:@"LCNetworkingReachabilityNotificationStatusItem"];
    }
    
    NSInteger status   = [statusStr integerValue];
    if (self.isFirstLoad == YES) {
        self.isFirstLoad = NO;
        self.networkStatus = status;
        return;
    }
    
    if (status == self.networkStatus)return;
    
    self.networkStatus = status;
    if (status != AFNetworkReachabilityStatusNotReachable && status != AFNetworkReachabilityStatusUnknown) {
        if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [[self class] connectedBy3GNetworkAlert];
        }else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            [AppDelegate connectedByWifiNetworkAlert];
        }else{
            [AppDelegate connectedByOtherNetworkAlert];
        }
    }else{
        [[self class] connectedByNoNetworkAlert];
    }
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectControl:(UIControl *)control {
    UIView *animationView;
    
    if ([control cyl_isTabButton]) {
        //更改红标状态
        if ([[self cyl_tabBarController].selectedViewController cyl_isShowTabBadgePoint]) {
            [[self cyl_tabBarController].selectedViewController cyl_removeTabBadgePoint];
        } else {
            [[self cyl_tabBarController].selectedViewController cyl_showTabBadgePoint];
        }

        animationView = [control cyl_tabImageView];
    }
//
//    // 即使 PlusButton 也添加了点击事件，点击 PlusButton 后也会触发该代理方法。
//    if ([control cyl_isPlusButton]) {
//        UIButton *button = CYLExternPlusButton;
//        animationView = button.imageView;
//    }
    
    //    if ([self cyl_tabBarController].selectedIndex % 2 == 0) {
    //        [self addScaleAnimationOnView:animationView repeatCount:1];
    //    } else {
    [self addRotateAnimationOnView:animationView];
    //    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
